//
//  JSearchProductController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/3.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JSearchProductController.h"
#import "JBaseCollectionViewCell.h"
#import "JProductDetailController.h"
#import "UICollectionView+JCollectionView.h"
#import "JEmptyDataView.h" // 空数据展示


#define orderBykey @"orderBy" //默认为1，价格升序为2，降序为4
#define pageIndexkey @"pageIndex"
#define pageSizekey @"pageSize"
#define keyWordkey @"keyWord"
#define categoryIdkey @"categoryId" // 0
#define vendorIdkey @"vendorId" // 0

// 搜索参数
//"orderBy":1,
//"pageIndex":1,
//"pageSize":10，
//keyWord："",
//orderBy:1， //默认为1，价格升序为2，降序为4
//CategoryId：0，
//VendorId：0


@interface JSearchProductController ()<UISearchBarDelegate ,UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic , strong) NSMutableArray *productArr;
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong) JEmptyDataView *emptyView;

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) JGetPageModel *pageModel;
@property (nonatomic, strong) NSMutableArray *btnArr;
@property (nonatomic, strong) UIView  *lineView;
@property (nonatomic, assign) NSInteger isDown; // 1 下， 2 上
@property (nonatomic, assign) NSInteger lestSelnum;
@property (nonatomic, strong) NSMutableDictionary *parameterDic;

@end

@implementation JSearchProductController

- (JGetPageModel *)pageModel
{
    if (!_pageModel) {
        _pageModel = [JGetPageModel new];
        _pageModel.orderBy = 1;   //默认为1，价格升序为2，降序为4
        _pageModel.pageIndex = 1;
        _pageModel.pageSize = 10;
        
    }
    return _pageModel;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _searchBar.text = @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [super InitUI];
    
    self.titleLabel.hidden = YES;
    self.leftButton.hidden = NO;
    self.rightButton.hidden = NO;
    _btnArr = [NSMutableArray array];
    _productArr = [NSMutableArray array];
    _parameterDic = [NSMutableDictionary dictionary];
    
    if (!self.CategoryId) {
        self.CategoryId = 0;
    }
    
    if (!self.VendorId) {
        self.VendorId = 0;
    }
    
    // 设置导航搜索栏
    [self setUpNav];
    
    [self setTopBtnSelConfigView];
    
    [self setConfigCollectView];
    
    [self setConfigEmptyView]; // 空数据展示

//    [self loadSearchProduct];
}

- (void)setConfigEmptyView
{
    _emptyView = [[JEmptyDataView alloc]initWithFrame:CGRectMake(0, 50, self.contentView.width, self.contentView.height - 50)];
    _emptyView.hidden = YES;
    [self.contentView addSubview:_emptyView];
}

// 配置导航栏
- (void)setUpNav
{
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    [self.rightButton setImage:[UIImage imageNamed:@"shopcarsmall"] forState:UIControlStateNormal];
    
    CGRect searchRect = CGRectMake(CGRectGetMaxX(self.leftButton.frame) + 5, 25, CGRectGetMinX(self.rightButton.frame) - 10 - CGRectGetMaxX(self.leftButton.frame), 32);
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:searchRect];
    searchBar.delegate = self;
    searchBar.backgroundColor = [UIColor clearColor];
    
    if (self.searchText.length > 0) {
        searchBar.text = self.searchText;
    }
    else
    {
        searchBar.placeholder = @"宝贝搜索";
    }
    
    for (UIView *subViews in searchBar.subviews) {
        if ([subViews isKindOfClass:[UIView class]]) {
            [[subViews.subviews objectAtIndex:0] removeFromSuperview];
            
            if ([[subViews.subviews objectAtIndex:0] isKindOfClass:[UITextField class]]) {
                UITextField *textF = [subViews.subviews objectAtIndex:0];
                textF.font = kFONT_TITLE(12);
                textF.backgroundColor = kRGBColor(240, 240, 240);
                
                UIColor *color = [UIColor grayColor];
                NSAttributedString *attri = [[NSAttributedString alloc]initWithString:@"宝贝搜索" attributes:@{NSForegroundColorAttributeName:color}];
                
                [textF setAttributedPlaceholder:attri];
            }
        }
    }
    
    [self.navigationView addSubview:searchBar];
    _searchBar = searchBar;
}

- (void)setTopBtnSelConfigView {
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.width, 50)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bottomView];
    
    NSArray *nameArr = @[@"销量",@"价格"];
    CGFloat selbtnWidth = bottomView.width/2.0;
    
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        collectBtn.frame = CGRectMake(selbtnWidth * i , 0, selbtnWidth, 40);
        collectBtn.titleLabel.font = kFONT_TITLE(14);
        [collectBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        [collectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [collectBtn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        collectBtn.tag = 10 + i;
        
        [collectBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i == 0) {
            collectBtn.selected = YES;
        }
        
        if (i == 1) {
            if (_isDown == 1) {
                [collectBtn setImage:[UIImage imageNamed:@"down_1"] forState:UIControlStateNormal];
            }
            else
            {
                [collectBtn setImage:[UIImage imageNamed:@"up_1"] forState:UIControlStateNormal];
            }
            
            [collectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
            [collectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 83, 0, 5)];
            
        }
        
        [bottomView addSubview:collectBtn];
        [_btnArr addObject:collectBtn];
    }
    
    _lineView = [[UIView alloc]initWithFrame:CGRectMake((selbtnWidth - 30)/2.0, 39, 30, 1)];
    _lineView.backgroundColor = [UIColor redColor];
    [bottomView addSubview:_lineView];
}

- (void)setConfigCollectView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    _collectView = [UICollectionView initWithCollectionView:CGRectMake(0, 50, kWindowW, CGRectGetHeight(self.contentView.frame) - 50) withDelegate:self];
    
//    __weak typeof(self) weakSelf = self;
    _collectView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (self.productArr.count == self.pageModel.pageIndex * self.pageModel.pageSize) {
            self.pageModel.pageIndex += 1;
            [self loadSearchProduct];
            [_collectView.mj_footer endRefreshing];
        }
        else if (self.productArr.count == 0)
        {
            [self loadSearchProduct];
            [_collectView.mj_footer endRefreshing];
        }
        else
        {
            [_collectView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    [_collectView.mj_footer beginRefreshing];
    
    
    // 注册cell
    [self.collectView registerClass:[JBaseCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([JBaseCollectionViewCell class])];
    
    [self.contentView addSubview:_collectView];
    
}


#pragma mark - searchBar
// searchBar
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
//    NSLog(@"===%@", searchBar.text);
    self.pageModel.pageIndex = 1;
    
    self.searchText = searchBar.text;
    
    [self.productArr removeAllObjects];
    [self loadSearchProduct];
    
    // 放弃作为第一个响应者，关闭键盘
    [searchBar resignFirstResponder];
    
}

/// 搜索请求
- (void)loadSearchProduct
{
    
    [SVProgressHUD show];
    [self setConfigRequestParameterMethod];
    NSString *url = @"Products/GetProducts";
    [JNetManager SearchProductRequestUrl:url
                                     dic:self.parameterDic
                                 success:^(id response) {
                                     [SVProgressHUD dismiss];
                                     if (response) {
                                         NSMutableArray *dataArr = (NSMutableArray *)response;
                                         [_productArr addObjectsFromArray:dataArr];
                                         
                                         if (self.productArr.count == 0) {
                                             self.emptyView.hidden = NO;
                                             self.collectView.hidden = YES;
                                         }
                                         else
                                         {
                                             self.emptyView.hidden = YES;
                                             self.collectView.hidden = NO;
                                             [self.collectView reloadData];
                                        }
                                         
                                     }
                                 } failure:^(NSString *err) {
                                     [SVProgressHUD dismiss];
                                     [SVProgressHUD showErrorWithStatus:err];
                                 }];
}

- (void)setConfigRequestParameterMethod
{
    if ([self.parameterDic objectForKey:orderBykey]) {
        [self.parameterDic removeObjectForKey:orderBykey];
        [self.parameterDic setObject:@(self.pageModel.orderBy) forKey:orderBykey];
    }
    else
    {
        [self.parameterDic setObject:@(self.pageModel.orderBy) forKey:orderBykey];
    }
    
    if ([self.parameterDic objectForKey:pageIndexkey]) {
        [self.parameterDic removeObjectForKey:pageIndexkey];
        [self.parameterDic setObject:@(self.pageModel.pageIndex) forKey:pageIndexkey];
    }
    else
    {
        [self.parameterDic setObject:@(self.pageModel.pageIndex) forKey:pageIndexkey];
    }
    
    if ([self.parameterDic objectForKey:pageSizekey]) {
        [self.parameterDic removeObjectForKey:pageSizekey];
        [self.parameterDic setObject:@(self.pageModel.pageSize) forKey:pageSizekey];
    }
    else
    {
        [self.parameterDic setObject:@(self.pageModel.pageSize) forKey:pageSizekey];
    }
    
    if ([self.parameterDic objectForKey:categoryIdkey]) {
        [self.parameterDic removeObjectForKey:categoryIdkey];
        [self.parameterDic setObject:@(self.CategoryId) forKey:categoryIdkey];
    }
    else
    {
        [self.parameterDic setObject:@(self.CategoryId) forKey:categoryIdkey];
    }
    
    if ([self.parameterDic objectForKey:vendorIdkey]) {
        [self.parameterDic removeObjectForKey:vendorIdkey];
        [self.parameterDic setObject:@(self.VendorId) forKey:vendorIdkey];
    }
    else
    {
        [self.parameterDic setObject:@(self.VendorId) forKey:vendorIdkey];
    }
    
    if (self.searchText.length > 0) {
        if ([self.parameterDic objectForKey:keyWordkey]) {
            [self.parameterDic removeObjectForKey:keyWordkey];
            [self.parameterDic setObject:self.searchText forKey:keyWordkey];
        }
        else
        {
            [self.parameterDic setObject:self.searchText forKey:keyWordkey];
        }
    }
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _productArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JBaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([JBaseCollectionViewCell class]) forIndexPath:indexPath];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (_productArr.count > indexPath.row) {
            cell.prodeutModel = _productArr[indexPath.row];
        }
        
    });
    
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellwidth = (kWindowW - 15*3)/2.0;
    return (CGSize){cellwidth,260};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 15, 15, 15);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}

#pragma mark ---- UICollectionViewDelegate

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    JProductDetailController *detail = [[JProductDetailController alloc]init];
    detail.productModel = _productArr[indexPath.row];
    detail.inputType = 1; // 表示非购物车进入商品详情
    [self.navigationController pushViewController:detail animated:YES];
}


- (void)btnClick:(UIButton *)btn
{
  
        if (btn.tag == 11) {
            if (btn.tag == _lestSelnum) {
                if (_isDown == 1) {
                    _isDown = 2 ;
                }
                else
                {
                    _isDown = 1;
                }
            }
            
            if (_isDown == 1) {
                [btn setImage:[UIImage imageNamed:@"down_1"] forState:UIControlStateNormal];
            }
            else
            {
                [btn setImage:[UIImage imageNamed:@"up_1"] forState:UIControlStateNormal];
            }
        }
        else
        {
            if (btn.tag == _lestSelnum) {
                return;
            }
        }
        
        for (UIButton *btn in self.btnArr) {
            btn.selected = NO;
        }
        btn.selected = YES;
        [self lineViewAnimation:btn.tag - 10];
        
        _lestSelnum = btn.tag;
    
    if (btn.tag == 10) {
        self.pageModel.orderBy = 1;
    }
    else
    {
        if (_isDown == 1) {
            self.pageModel.orderBy = 4;

        }
        else
        {
            self.pageModel.orderBy = 2;

        }
    }
    [self.view endEditing:YES];
    
    [_productArr removeAllObjects];
    self.pageModel.pageIndex = 1;
    [self loadSearchProduct];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonClick:(UIButton *)rightButton
{
    // 前往购物车
   JGoShopCarViewController
}


- (void)lineViewAnimation:(NSInteger)num
{
    
    [UIView animateWithDuration:0.3 animations:^{
        _lineView.frame = CGRectMake((self.contentView.width/2.0 - 30)/2.0 + num * self.contentView.width/2.0, _lineView.origin.y, _lineView.width, _lineView.height);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
